

package com.zdkj.subway.epm.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.epm.entity.SwExTicketOperation;
import com.zdkj.subway.epm.service.SwExTicketOperationService;
import com.zdkj.subway.epm.util.LocalDateConverter;
import com.zdkj.subway.epm.util.LocalDateTimeConverter;
import com.zdkj.subway.epm.util.SelMapUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;


/**
 * 票务运作问题
 *
 * @author chenbo
 * @date 2020-06-04 17:30:47
 */
@RestController
@AllArgsConstructor
@RequestMapping("/swexticketoperation")
@Api(value = "swexticketoperation", tags = "票务运作问题管理")
public class SwExTicketOperationController {
    //通知状态
    private final static String NOTICE_STATUS_NO = "0";
    private final static String NOTICE_STATUS_YES = "1";
    private final static String NOTICE_STATUS_Re = "2";
    //发送短款状态
    private final static String SEND_STATUS_NO = "0";
    private final static String SEND_STATUS_YES = "1";
    private final static String SEND_STATUS_CANCEL = "2";
    //反馈状态
    private final static String BACK_STATUS_NO = "0";
    private final static String BACK_STATUS_YES = "1";

    private final SwExTicketOperationService swExTicketOperationService;

    /**
     * 分页查询
     *
     * @param page                分页对象
     * @param swExTicketOperation 票务运作问题
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    public R getSwExTicketOperationPage(Page page, SwExTicketOperation swExTicketOperation) {
        IPage selList;
        List<String> dateCondition = swExTicketOperation.getDates1();
        if (SecurityUtils.getUser().getBelongToLine()) {
            //先查询未通知的
            /*if(StringUtils.isEmpty(swExTicketOperation.getNoticeStatus())){
                swExTicketOperation.setNoticeStatus("0");
            }*/
            if(CollectionUtil.isNotEmpty(dateCondition)){
                selList = swExTicketOperationService.page(page, Wrappers.query(swExTicketOperation).lambda().between(SwExTicketOperation::getNoticeTime,dateCondition.get(0),dateCondition.get(1)));
            }else {
                selList = swExTicketOperationService.page(page, Wrappers.query(swExTicketOperation));
            }
        } else {
            if(CollectionUtil.isNotEmpty(dateCondition)){
                selList = swExTicketOperationService.page(page, Wrappers.query(swExTicketOperation)
                        .lambda().eq(SwExTicketOperation::getLineCode, SecurityUtils.getUser().getLineCode())
                        .eq(SwExTicketOperation::getStationCode, SecurityUtils.getUser().getStationCode())
                        .and(i -> i.eq(SwExTicketOperation::getNoticeStatus, NOTICE_STATUS_YES).or()
                                .eq(SwExTicketOperation::getNoticeStatus, NOTICE_STATUS_Re))
                        .between(SwExTicketOperation::getNoticeTime,dateCondition.get(0),dateCondition.get(1))
                );
            }else{
                selList = swExTicketOperationService.page(page, Wrappers.query(swExTicketOperation)
                        .lambda().eq(SwExTicketOperation::getLineCode, SecurityUtils.getUser().getLineCode())
                        .eq(SwExTicketOperation::getStationCode, SecurityUtils.getUser().getStationCode())
                        .and(i -> i.eq(SwExTicketOperation::getNoticeStatus, NOTICE_STATUS_YES).or()
                                .eq(SwExTicketOperation::getNoticeStatus, NOTICE_STATUS_Re))
                        );
            }
        }
        return R.ok(selList);
    }

    /**
     * 导出
     *
     * @param page                分页对象
     * @param swExTicketOperation 票务运作问题导出
     * @return
     */
    @ApiOperation(value = "票务运作问题导出", notes = "票务运作问题导出")
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('epm_swexticketoperation_export')")
    public void getSwExTicketOperationExport(Page page, SwExTicketOperation swExTicketOperation, HttpServletResponse response) throws IOException {
        IPage selList;
        if (SecurityUtils.getUser().getBelongToLine()) {
            selList = swExTicketOperationService.export(page, Wrappers.query(swExTicketOperation)
                    .allEq(SelMapUtils.getSwExTicketOperationStationExportMap(swExTicketOperation)));
        } else {
            selList = swExTicketOperationService.export(page,Wrappers.query(swExTicketOperation)
                    .allEq(SelMapUtils.getSwExTicketOperationStationExportMap(swExTicketOperation))
            .eq("a.STATION_CODE",SecurityUtils.getUser().getStationCode())
            .ne("a.NOTICE_STATUS",NOTICE_STATUS_NO));
        }
        // 写法1
        String fileName = URLEncoder.encode("票务运作问题", "UTF-8");
        //"C:\\Users\\Administrator\\Desktop\\" + "simpleWrite" + System.currentTimeMillis() + ".xlsx";
        // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
        // 如果这里想使用03 则 传入excelType参数即可

        response.setHeader("Content-disposition", "attachment;filename=" + fileName + SelMapUtils.getDatetimeNowFormatter() + ".xlsx");
        EasyExcel.write(response.getOutputStream(), SwExTicketOperation.class).registerConverter(new LocalDateTimeConverter())
                .registerConverter(new LocalDateConverter()).sheet("票务运作问题")
                .doWrite(selList.getRecords());
    }

    /**
     * 票务运作问题批量通知
     *
     * @param swExTicketOperation 票务运作问题
     * @return R
     */
    @ApiOperation(value = "票务运作问题批量通知", notes = "票务运作问题批量通知")
    @SysLog("票务运作问题批量通知")
    @PutMapping("noticeBatch")
    @PreAuthorize("@pms.hasPermission('epm_swexticketoperation_noticeBatch')")
    public R noticeBatch(@RequestBody List<SwExTicketOperation> swExTicketOperation) {
        if (SecurityUtils.getUser().getBelongToLine()) {
            for (SwExTicketOperation e : swExTicketOperation) {
                e.setNoticeTime(LocalDate.now());
                e.setNoticeStatus(NOTICE_STATUS_YES);
            }
            return R.ok(swExTicketOperationService.updateBatchById(swExTicketOperation));
        } else {
            for (SwExTicketOperation e : swExTicketOperation) {
                if (e.getNoticeStatus().equals(NOTICE_STATUS_YES)) {
                    e.setBackTime(LocalDate.now());
                    e.setNoticeStatus(NOTICE_STATUS_Re);
                    e.setBackStatus(BACK_STATUS_YES);
                }
            }
            return R.ok(swExTicketOperationService.updateBatchById(swExTicketOperation));
        }
    }

    /**
     * 票务运作问题发送短款
     *
     * @param swExTicketOperation 票务运作问题
     * @return R
     */
    @ApiOperation(value = "票务运作问题发送短款", notes = "票务运作问题发送短款")
    @SysLog("票务运作问题发送短款")
    @PutMapping("sendBatch")
    @PreAuthorize("@pms.hasPermission('epm_swexticketoperation_sendBatch')")
    public R sendBatch(@RequestBody List<SwExTicketOperation> swExTicketOperation) {
        //TODO 调用收入审核售票员票短款接口同步数据
        for (SwExTicketOperation e : swExTicketOperation) {
            if (e.getSendShortStatus().equals(SEND_STATUS_NO) || e.getSendShortStatus().equals(SEND_STATUS_CANCEL)) {
                e.setSendShortStatus(SEND_STATUS_YES);
            }
        }
        return R.ok(swExTicketOperationService.updateBatchById(swExTicketOperation));
    }

    /**
     * 票务运作问题撤销短款
     *
     * @param swExTicketOperation 票务运作问题
     * @return R
     */
    @ApiOperation(value = "票务运作问题撤销短款", notes = "票务运作问题撤销短款")
    @SysLog("票务运作问题撤销短款")
    @PutMapping("cancelBatch")
    @PreAuthorize("@pms.hasPermission('epm_swexticketoperation_cancelBatch')")
    public R cancelBatch(@RequestBody List<SwExTicketOperation> swExTicketOperation) {
        //TODO 调用收入审核售票员票短款接口同步数据
        for (SwExTicketOperation e : swExTicketOperation) {
            if (!e.getNoticeStatus().equals(NOTICE_STATUS_Re)) {
                e.setSendShortStatus(SEND_STATUS_CANCEL);
            }
        }
        return R.ok(swExTicketOperationService.updateBatchById(swExTicketOperation));
    }


    /**
     * 通过ids删除票务运作问题
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过ids删除票务运作问题", notes = "通过ids删除票务运作问题")
    @SysLog("通过ids删除票务运作问题")
    @DeleteMapping("/delBatch")
    @PreAuthorize("@pms.hasPermission('epm_swexticketoperation_dels')")
    public R removeByIds(@RequestBody List<Integer> id) {
        if (id.size()==0){
            return R.ok();
        }
        return R.ok(swExTicketOperationService.removeByIds(id));
    }

    /**
     * 通过id查询票务运作问题
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(swExTicketOperationService.getById(id));
    }

    /**
     * 新增票务运作问题
     *
     * @param swExTicketOperation 票务运作问题
     * @return R
     */
    @ApiOperation(value = "新增票务运作问题", notes = "新增票务运作问题")
    @SysLog("新增票务运作问题")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('epm_swexticketoperation_add')")
    public R save(@RequestBody SwExTicketOperation swExTicketOperation) {
        swExTicketOperation.setSendShortStatus(SEND_STATUS_NO);
        swExTicketOperation.setNoticeStatus(NOTICE_STATUS_NO);
        swExTicketOperation.setBackStatus(BACK_STATUS_NO);
        swExTicketOperation.setCreateTime(LocalDateTime.now());
        return R.ok(swExTicketOperationService.save(swExTicketOperation));
    }

    /**
     * 修改票务运作问题
     *
     * @param swExTicketOperation 票务运作问题
     * @return R
     */
    @ApiOperation(value = "修改票务运作问题", notes = "修改票务运作问题")
    @SysLog("修改票务运作问题")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('epm_swexticketoperation_edit')")
    public R updateById(@RequestBody SwExTicketOperation swExTicketOperation) {
        return R.ok(swExTicketOperationService.updateById(swExTicketOperation));
    }

    /**
     * 通过id删除票务运作问题
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除票务运作问题", notes = "通过id删除票务运作问题")
    @SysLog("通过id删除票务运作问题")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('epm_swexticketoperation_del')")
    public R removeById(@PathVariable Integer id) {
        return R.ok(swExTicketOperationService.removeById(id));
    }

}
